package cn.ibizlab.core.oauth2.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.util.Map;
import static cn.ibizlab.core.oauth2.constants.OAuth2Constant.*;

/**
 * OAuth2登录切面：密码模式登录前清除登录用户缓存
 */
@Aspect
@Component
@ConditionalOnProperty(name = "ibiz.auth.security", havingValue = "oauth2", matchIfMissing = true)
public class OAuth2LoginAspect {

    @Autowired
    @Lazy
    cn.ibizlab.util.security.AuthUserServiceImpl authUserService;

    @Before(value = "execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(..)) || execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public void beforeCreate(JoinPoint point){
        Object[] args = point.getArgs();
        if(ObjectUtils.isEmpty(args) || args.length !=2)
            return;

        Map<String, String> parameters = (Map<String, String>) args[1];
        if(!ObjectUtils.isEmpty(parameters) && REQUEST_PARAM_GRANTTYPE_PASSWORD.equals(parameters.get(REQUEST_PARAM_GRANTTYPE))
                                            && !ObjectUtils.isEmpty(parameters.get(REQUEST_PARAM_USERNAME))){
            //登录前清除用户缓存
            authUserService.resetByUsername(parameters.get(REQUEST_PARAM_USERNAME));
        }
    }

}
